
package com.gcloud.mesh.dcs.dao;

import java.util.ArrayList;
import java.util.List;

import com.google.api.client.util.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.gcloud.framework.db.PageResult;
import com.gcloud.framework.db.dao.impl.JdbcBaseDaoImpl;
import com.gcloud.mesh.dcs.entity.AppEntity;
import com.gcloud.mesh.dcs.enums.AppType;
import com.gcloud.mesh.dcs.service.AuthorityService;
import com.gcloud.mesh.header.enums.AuthorityResourceClassification;
import com.gcloud.mesh.header.msg.dcs.ListByClassificationMsg;
import com.gcloud.mesh.header.vo.dcs.AppItemVo;
import com.gcloud.mesh.header.vo.dcs.AppVo;
import com.gcloud.mesh.header.vo.dcs.AuthorityVo;

@Repository
public class AppDao extends JdbcBaseDaoImpl<AppEntity, String> {

	@Autowired
	private AuthorityService authorityService;

	public AppVo getVoById(String id) {
		List<Object> values = new ArrayList<>();
		values.add(id);
		List<AppVo> apps = this.findBySql("SELECT a.*, r.datacenter_id AS datacenterId FROM dcs_apps a LEFT JOIN asset_cloud_resources r ON r.id = a.cloud_resource_id WHERE a.id = ? ", values, AppVo.class);
		if (apps != null && apps.size() > 0) {
			return apps.get(0);
		} else {
			return null;
		}
	}

	public <E> PageResult<E> page(String name, Integer type, String cloudResourceId, int pageNo, int pageSize, Class<E> clazz, String datacenterId) {
		List<Object> values = new ArrayList<>();

		StringBuilder sb = new StringBuilder();
		sb.append("SELECT a.*, c.name AS cloudResourceName, c.datacenter_id AS datacenter_id  FROM dcs_apps a LEFT JOIN asset_cloud_resources c ON a.cloud_resource_id = c.id WHERE 1=1 ");

		if (type != null) {
			sb.append(" AND a.type = ? ");
			values.add(type);
		}

		if (StringUtils.isNotBlank(name)) {
			sb.append(" AND a.name LIKE concat('%', ?, '%')");
			values.add(name);
		}
		
		if (StringUtils.isNotBlank(cloudResourceId)) {
			sb.append(" AND a.cloud_resource_id = ?");
			values.add(cloudResourceId);
		}
		if(StringUtils.isNotBlank(datacenterId)) {
			sb.append(" AND c.datacenter_id = ?");
			values.add(datacenterId);
		}
		
		sb.append(" AND (deleted = 0 or deleted is null) ");

		checkResourceAuthority(sb);

		sb.append(" ORDER BY a.create_time desc ");
		return this.findBySql(sb.toString(), values, pageNo, pageSize, clazz);
	}

	private StringBuilder checkResourceAuthority(StringBuilder sql) {

		ListByClassificationMsg msg = new ListByClassificationMsg();
		msg.setClassification(AuthorityResourceClassification.APP.getName());
		List<AuthorityVo> authorities = null;
		try {
			authorities = authorityService.listByClassification(msg);
		} catch (Exception e) {

		}
		if(authorities != null) {
			for (AuthorityVo vo : authorities) {
				if (!vo.getEnabled()) {
					sql.append(" and a.from != 'sync' ");
					break;
				}
			}
		}

		return sql;
	}

	public List<AppVo> getByDatacenterId(String datacenterId) {
		List<Object> values = new ArrayList<>();
		values.add(datacenterId);
		return this.findBySql("SELECT a.*, r.datacenter_id AS datacenterId FROM dcs_apps a LEFT JOIN asset_cloud_resources r ON r.id = a.cloud_resource_id WHERE r.datacenter_id = ? ", values, AppVo.class);
	}
	
	public List<AppVo> getByResourceId(String resourceId) {
		List<Object> values = new ArrayList<>();
		values.add(resourceId);
		return this.findBySql("SELECT a.*, r.datacenter_id AS datacenterId FROM dcs_apps a LEFT JOIN asset_cloud_resources r ON r.id = a.cloud_resource_id WHERE a.cloud_resource_id = ? ", values, AppVo.class);
	}
	
	public int count() {
		StringBuilder sql = new StringBuilder("SELECT COUNT(*) FROM dcs_apps WHERE 1=1");
		return this.countBySql(sql.toString(), new ArrayList<Object>());
	}
	
	public List<AuthorityVo> listAuthority(String classification) {
		ListByClassificationMsg msg = new ListByClassificationMsg();
		msg.setClassification(classification);
		List<AuthorityVo> authorities = null;
		try {
			authorities = authorityService.listByClassification(msg);
		}catch(Exception e) {
			
		}
		return authorities;
	}

    public boolean isSyncProcess(String appId) {
		String sql = "select count(*) from dcs_apps a inner join dcs_scheduler_jobs j on j.app_id = a.id where a.id = ? and j.status <= 1 ";
		List<Object> list = Lists.newArrayList();
		list.add(appId);
		return this.countBySql(sql, list)>0?true:false;

    }
	public void updateAppResourceIdAndDataCenterId(String appId, String destResourceId) {
		super.jdbcTemplate.update("update dcs_apps set cloud_resource_id = ? where id = ?",destResourceId, appId);
	}

	public AppItemVo getByAppId(String appId) {
		StringBuffer sb = new StringBuffer();
		List<Object> list = Lists.newArrayList();
		sb.append("SELECT a.*, c.name AS cloudResourceName FROM dcs_apps a LEFT JOIN asset_cloud_resources c ON a.cloud_resource_id = c.id WHERE a.id = ? ");
		list.add(appId);
		List<AppItemVo> vos = findBySql(sb.toString(), list, AppItemVo.class);
		if(vos != null && !vos.isEmpty()) {
			return vos.get(0);
		}
		return null;
	}
	
	public int countDatacenterApp(String srcdatacenterId) {
		StringBuffer buff = new StringBuffer();
		List<Object> list = Lists.newArrayList();
		buff.append(" SELECT a.* FROM dcs_apps a LEFT JOIN asset_cloud_resources c ON a.cloud_resource_id = c.id WHERE c.datacenter_id = ? ");
		list.add(srcdatacenterId);
		List<AppEntity> vos = findBySql(buff.toString(), list, AppEntity.class);
		if(vos == null || vos.isEmpty()) {
			return 0;
		}
		return 1;
	}

}
